package star.oath.framework.generate.template;

import star.oath.framework.generate.CodeGenerator;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class MapperInterfaceTemplate {
    /**
     * 根据实体类的全限定名生成对应的 Mapper 接口文件
     * @param fullyQualifiedEntityName
     */
    public void generateMapperInterface(String fullyQualifiedEntityName) {
        if (fullyQualifiedEntityName == null || fullyQualifiedEntityName.trim().isEmpty()) {
            throw new IllegalArgumentException("实体类全限定名不能为空");
        }

        // 1. 拆分类名和包名
        int lastDot = fullyQualifiedEntityName.lastIndexOf('.');
        if (lastDot == -1) {
            throw new IllegalArgumentException("无效的全限定类名: " + fullyQualifiedEntityName);
        }

        String packageName = fullyQualifiedEntityName.substring(0, lastDot);
        String className = fullyQualifiedEntityName.substring(lastDot + 1);

        // 2. 校验类名合法性
        if (!CodeGenerator.VALID_CLASS_NAME.matcher(className).matches()) {
            throw new IllegalArgumentException("非法的类名: " + className);
        }

        // 3. 检查是否在 model 包下
        if (!packageName.endsWith(".model")) {
            throw new IllegalArgumentException("实体类必须位于 .model 包下，当前包: " + packageName);
        }

        // 4. 替换 .model 为 .mapper
        String mapperPackageName = packageName.substring(0, packageName.length() - "model".length()) + "mapper";

        // 5. 构建 Mapper 接口内容
        String mapperContent = String.format(
                "package %s;\n\n" +
                        "import com.baomidou.mybatisplus.core.mapper.BaseMapper;\n" +
                        "import %s;\n\n" +
                        "public interface %sMapper extends BaseMapper<%s> {\n" +
                        "}\n",
                mapperPackageName,
                fullyQualifiedEntityName,
                className,
                className
        );

        // 6. 转换包名为目录路径（使用系统分隔符）
        String mapperDirPath = CodeGenerator.SRC_MAIN_JAVA + mapperPackageName.replace('.', '/');
        Path mapperDir = Paths.get(mapperDirPath);
        try {
            Files.createDirectories(mapperDir); // 自动创建多级目录
            Path mapperFile = mapperDir.resolve(className + "Mapper.java");
            Files.write(mapperFile, mapperContent.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
            System.out.println("✅ Mapper 接口已生成: " + mapperFile.toAbsolutePath());
        } catch (IOException e) {
            System.err.println("❌ 生成 Mapper 文件失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}